package com.linq.cool.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linq.cool.api.domain.SysDept;
import com.linq.cool.common.constants.UserConstants;
import com.linq.cool.common.core.domain.BaseController;
import com.linq.cool.common.core.domain.Result;
import com.linq.cool.common.core.utils.BeanUtils;
import com.linq.cool.common.core.utils.SecurityUtils;
import com.linq.cool.common.core.utils.StringUtils;
import com.linq.cool.common.log.annotation.Log;
import com.linq.cool.common.log.enums.BusinessType;
import com.linq.cool.common.security.annotation.PreAuthorize;
import com.linq.cool.system.dto.SysDeptQueryDTO;
import com.linq.cool.system.service.SysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: yqlin
 * @Date: 2021/1/22 22:29
 * @Description: 部门
 * @Version: 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("dept")
public class SysDeptController extends BaseController {
    @Autowired
    private SysDeptService sysDeptService;

    /**
     * 获取部门下拉树列表
     *
     * @return 部门树状下拉列表
     */
    @GetMapping("getTreeSelect")
    public Result<?> getTreeSelect() {
        List<SysDept> depts = sysDeptService.list();
        return Result.ok(sysDeptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     *
     * @param roleId 角色id
     *
     * @return 结果
     */
    @GetMapping(value = "/getRoleDeptTreeSelect/{roleId}")
    public Result<?> roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysDept> depts = sysDeptService.list(new LambdaQueryWrapper<SysDept>()
                                                          .eq(SysDept::getIsDeleted, UserConstants.StateEnum.STATUS_NORMAL.getCode())
                                                          .orderByAsc(SysDept::getParentId)
                                                          .orderByAsc(SysDept::getSort)
        );
        Map<String, Object> map = new HashMap<>(2);
        map.put("checkedKeys", sysDeptService.listByRoleId(roleId));
        map.put("depts", sysDeptService.buildDeptTreeSelect(depts));
        return Result.ok(map);
    }

    /**
     * 获取部门列表
     *
     * @param dto 部门信息
     *
     * @return 结果
     */
    @PreAuthorize(hasPerm = "sys:dept:list")
    @GetMapping("list")
    public Result<?> list(SysDeptQueryDTO dto) {
        log.info("SysDeptQueryDTO: {}", dto);
        SysDept dept = new SysDept();
        BeanUtils.copyProperties(dto, dept);
        return Result.ok(sysDeptService.listByParams(dept));
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize(hasPerm = "sys:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public Result<?> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = sysDeptService.listByParams(new SysDept());
        depts.removeIf(d -> d.getId().intValue() == deptId
                || ArrayUtils.contains(StringUtils.split(d.getAncestorIds(), ","), deptId + ""));
        return Result.ok(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize(hasPerm = "system:dept:query")
    @GetMapping(value = "/{deptId}")
    public Result<?> getInfo(@PathVariable Long deptId) {
        return Result.ok(sysDeptService.getById(deptId));
    }


    /**
     * 新增部门
     */
    @Log(moduleTitle = "部门管理", businessType = BusinessType.INSERT)
    @PreAuthorize(hasPerm = "sys:dept:add")
    @PostMapping
    public Result<?> add(@Validated @RequestBody SysDept dept) {
        if (sysDeptService.checkNameUnique(dept)) {
            return Result.fail("新增部门'" + dept.getName() + "'失败，部门名称已存在");
        }
        dept.setCreator(SecurityUtils.getUserId());
        return this.toResult(sysDeptService.saveDept(dept));
    }

    /**
     * 修改部门
     */
    @Log(moduleTitle = "部门管理", businessType = BusinessType.UPDATE)
    @PreAuthorize(hasPerm = "sys:dept:edit")
    @PutMapping
    public Result<?> edit(@Validated @RequestBody SysDept dept) {
        if (sysDeptService.checkNameUnique(dept)) {
            return Result.fail("修改部门'" + dept.getName() + "'失败，部门名称已存在");
        }
        if (dept.getParentId().equals(dept.getId())) {
            return Result.fail("修改部门'" + dept.getName() + "'失败，上级部门不能是自己");
        }
        if (UserConstants.StateEnum.STATUS_DISABLE.getCode().equals(dept.getStatus())
                && sysDeptService.checkNormalChild(dept.getId())) {
            return Result.fail("该部门包含未停用的子部门！");
        }
        dept.setModifier(SecurityUtils.getUserId()).setGmtModified(new Date());
        return this.toResult(sysDeptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @Log(moduleTitle = "部门管理", businessType = BusinessType.DELETE)
    @PreAuthorize(hasPerm = "sys:dept:remove")
    @DeleteMapping("{deptId}")
    public Result<?> remove(@PathVariable Long deptId) {
        if (sysDeptService.hasChild(deptId)) {
            return Result.fail("存在下级部门,不允许删除");
        }
        if (sysDeptService.checkExistUser(deptId)) {
            return Result.fail("部门存在用户,不允许删除");
        }
        return this.toResult(sysDeptService.removeById(deptId));
    }
}
